package com.wpw.dream.util.excel;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;

/**
 * easyExcel工具类
 * 
 * Project Name：dream-web
 * ClassName：EasyeExcelUtils
 * Description：
 * @author: wupengwei
 * @date: 2018年12月25日 上午11:44:44
 * note:
 *
 */
public class EasyeExcelUtils {
	
	private static Logger logger = LoggerFactory.getLogger(EasyeExcelUtils.class);
	
	/**
	 * 解析excel数据，
	 * @Description：
	 * @author: wupengwei
	 * @date: 2018年12月25日 上午11:30:57
	 * @param relationFile
	 * @param targetClass
	 * @param eventListener
	 * @return	数据结果集合
	 */
	public static <T extends BaseRowModel> List<T> parseExcel(MultipartFile relationFile,Class<T> targetClass, ExcelListener<T> eventListener) {
		String fileName = relationFile.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		InputStream inputStream = null;
		try {
			inputStream = relationFile.getInputStream();
			ExcelTypeEnum excelType;
			if (fileType.equals(".xls")) {
				excelType = ExcelTypeEnum.XLS;
			} else {
				excelType = ExcelTypeEnum.XLSX;
			}
			logger.info("开始解析文档");
			long start = System.currentTimeMillis();
			ExcelReader excelReader = new ExcelReader(inputStream, excelType, null, eventListener);
			excelReader.read(new Sheet(1, 1, targetClass));
			logger.info("解析文档耗时：" + (System.currentTimeMillis() - start) + "ms");

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return eventListener.getDataList();
	}

}

